import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QPushButton, 
    QVBoxLayout, QFileDialog, QLabel, QMessageBox, 
    QProgressBar, QHBoxLayout
)
from PyQt5.QtCore import QThread
from .converter import PDFConverter

class ConversionThread(QThread):
    """
    后台转换线程，防止GUI冻结
    """
    def __init__(self, converter, method, *args, **kwargs):
        super().__init__()
        self.converter = converter
        self.method = method
        self.args = args
        self.kwargs = kwargs

    def run(self):
        # 执行转换方法
        self.method(*self.args, **self.kwargs)

class PDFConverterGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.converter = PDFConverter()
        self.initUI()
        self.setup_signals()

    def initUI(self):
        self.setWindowTitle('PDF转Word转换器')
        self.setGeometry(300, 300, 500, 400)

        layout = QVBoxLayout()

        # 单文件转换按钮
        single_btn = QPushButton('选择PDF文件转换')
        single_btn.clicked.connect(self.convert_single_file)
        layout.addWidget(single_btn)

        # 批量转换按钮
        batch_btn = QPushButton('选择PDF文件夹批量转换')
        batch_btn.clicked.connect(self.batch_convert)
        layout.addWidget(batch_btn)

        # 进度条
        progress_layout = QHBoxLayout()
        self.progress_label = QLabel('转换进度：')
        self.progress_bar = QProgressBar()
        progress_layout.addWidget(self.progress_label)
        progress_layout.addWidget(self.progress_bar)
        layout.addLayout(progress_layout)

        # 状态标签
        self.status_label = QLabel('准备就绪')
        layout.addWidget(self.status_label)

        self.setLayout(layout)

    def setup_signals(self):
        """
        连接转换信号
        """
        self.converter.signals.progress_updated.connect(self.update_progress)
        self.converter.signals.conversion_finished.connect(self.on_conversion_finished)

    def update_progress(self, value):
        """
        更新进度条
        """
        self.progress_bar.setValue(value)
        self.status_label.setText(f'转换进度：{value}%')

    def on_conversion_finished(self, success, message):
        """
        转换完成后的处理
        """
        if success:
            QMessageBox.information(self, '成功', f'文件转换成功：{message}')
        else:
            QMessageBox.warning(self, '失败', f'文件转换失败：{message}')

    def convert_single_file(self):
        # 选择PDF文件
        pdf_path, _ = QFileDialog.getOpenFileName(self, '选择PDF文件', '', 'PDF文件 (*.pdf)')
        
        if pdf_path:
            # 自动生成输出路径：源文件目录 + 源文件名（扩展名改为.docx）
            docx_path = os.path.splitext(pdf_path)[0] + '.docx'
            
            # 重置进度条
            self.progress_bar.setValue(0)
            
            # 创建后台线程执行转换
            self.conversion_thread = ConversionThread(
                self.converter, 
                self.converter.convert_single_file, 
                pdf_path, 
                docx_path
            )
            self.conversion_thread.start()

    def batch_convert(self):
        # 选择PDF文件夹
        pdf_folder = QFileDialog.getExistingDirectory(self, '选择PDF文件夹')
        
        if pdf_folder:
            # 自动使用源文件夹作为输出文件夹
            output_folder = pdf_folder
            
            # 重置进度条
            self.progress_bar.setValue(0)
            
            # 创建后台线程执行批量转换
            self.conversion_thread = ConversionThread(
                self.converter, 
                self.converter.batch_convert, 
                pdf_folder, 
                output_folder
            )
            self.conversion_thread.start()

def run_gui():
    app = QApplication(sys.argv)
    ex = PDFConverterGUI()
    ex.show()
    sys.exit(app.exec_())